# coding: utf-8
import pandas as pd
from scipy import optimize


def xnpv(rate: float, df: pd.DataFrame):
    return sum(
        [row["money"] / (1 + rate) ** ((row["date"] - df.iloc[0, 0]).days / 365.25) for index, row in df.iterrows()])


def xirr(df: pd.DataFrame, guess=0) -> float:
    df['money'] = df['money'].astype('float64')
    try:
        return optimize.newton(lambda r: xnpv(r, df), guess)
    except Exception as e:
        print(str(e))
